package com.firefightingiot_data.data.common.base;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.firefightingiot_data.data.common.utils.appkit.ConfigKit;
import com.firefightingiot_data.data.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot_data.data.support.model.RespEntity;
import com.firefightingiot_data.data.support.utils.MyLogger;
import com.firefightingiot_data.data.support.utils.json.JsonKeyEdit;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class BaseService {

    @Resource
    public MyLogger logger;
    @Resource
    HttpServletRequest httpServletRequest;
    HttpResponse httpResponse;

    public List<?> toTimeStr(List<? extends Map> list, String datePattern) {
        for (Map map : list) {
            map.forEach((k, v) -> {
                if (v instanceof Timestamp) {
                    map.put(k, DateUtil.format(new Date(((Timestamp) v).getTime()), datePattern));
                }
            });
        }
        return list;
    }

    public Map<String, Object> toTimeStr(Map param, String datePattern) {
        param.forEach((k, v) -> {
            if (v instanceof Timestamp) {
                param.put(k, DateUtil.format(new Date(((Timestamp) v).getTime()), datePattern));
            }
        });
        return param;
    }

    public Map<String, Object> toTimeStr(Map param) {
        return toTimeStr(param, DatePattern.NORM_DATE_PATTERN);
    }

    public List<?> toTimeStr(List<? extends Map> list) {
        return toTimeStr(list, DatePattern.NORM_DATE_PATTERN);
    }

//    public IPage toTimeStr(IPage iPage, String datePattern) {
//        List list = iPage.getRecords();
//        iPage.setRecords(toTimeStr(list, datePattern));
//        return iPage;
//    }
//
//    public IPage toTimeStr(IPage iPage) {
//        return toTimeStr(iPage, DatePattern.NORM_DATE_PATTERN);
//    }

    //事务相关开始

    protected int batchCount = 1000;// 每批commit的个数

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 获取session
     *
     * @return session对象
     * @author <br>
     */
    public SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    }

    /**
     * 获取request操作对象
     *
     * @return request操作对象
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取request操作对象
     *
     * @return request操作对象
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取session操作对象
     *
     * @return session操作对象
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }


    public <A> A getMapper(SqlSession session, Class<A> type) {
        return session.getMapper(type);
    }

    public void commit(SqlSession session) {
        if (session != null) {
            session.commit();
            // 清理缓存，防止溢出
            session.clearCache();
        }
    }

    public void rollback(SqlSession session) {
        if (session != null)
            session.rollback();
    }

    public void closeSession(SqlSession session) {
        if (session != null)
            session.close();
    }

    /**
     * 大量数据批量插入
     *
     * @author <br>
     */
    public class BigData {
        List<?> list = new ArrayList<>();

        public BigData(List<?> list) {
            this.list = list;
        }

        public int getNum() {
            return (int) Math.ceil(list.size() / (batchCount * 1.0));
        }

        @SuppressWarnings("unchecked")
        public <TNT> TNT getData(int i) {
            return (TNT) list.subList(i * batchCount, ((i + 1) * batchCount) > list.size() ? list.size() : (i + 1) * batchCount);
        }
    }

    //获取用户id
    public String getUserId() {
        return "1";
    }

    //获取部门id
    public String getDeptId() {
        return "1";
    }

    //获取机构id
    public String getOrgId() {
        return "1";
    }

    //返回二进制流，下载用
    public ResponseEntity<byte[]> downloadExcel(@RequestParam("fileName") String fileName) throws IOException {
        String fileSavePath = ConfigKit.getStr("excelSavePath", "excel");
        String path = fileSavePath + fileName;
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    // rest调用包装开始----------------------------------------------------------------------------------------------------------------------------

    //一企一档
    public RespEntity business(JSONObject jsonParam, String key, String gp) {
        String ip = ConfigKit.getStr("businessJava", "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam);
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.getInteger("code") == 1) {
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            if (jsonObject.get("data") == null) {
                return RespEntity.success(jsonObject.get("data"));
            } else if (jsonObject.get("data") instanceof com.alibaba.fastjson.JSONObject) {
                return RespEntity.success(JSONUtil.parseObj(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONObject("data").toJSONString())));
            } else {
                return RespEntity.success(JSONUtil.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString())));
            }
        } else {
            return RespEntity.success();
        }
    }

    //消防物联网
    public RespEntity fireFightingiot(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.getInteger("code") == 1) {
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            return RespEntity.success(jsonObject.get("data"));
        } else {
            return RespEntity.success();
        }
    }

    //消防物联网:token版本
    public RespEntity fireFightingiotForToken(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        if (state == 401) return RespEntity.expire();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.get("code") == null) {//针对设备端的转发接口加的，它没有返回code
            return RespEntity.success();
        }
        if (jsonObject.getInteger("code") == 1) {
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            return RespEntity.success(jsonObject.get("data"));
        } else {
            if (jsonObject.get("data") != null) {
                return RespEntity.success(jsonObject.get("data"));
            }
            return RespEntity.success();
        }
    }

    //消防物联网对接
    public RespEntity fireFightingiotTwo(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (jsonObject.containsKey("result") && !jsonObject.getBoolean("result")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            return RespEntity.success(jsonObject.get("data"));
        } else {
            return RespEntity.success(jsonObject);
        }
//        return RespEntity.success(jsonObject);
    }

    //消防物联网对接
    public RespEntity fireFightingiotHandle(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        if (configKey.equals("Intelligentfire")) {
            logger.info("----------------------------Intelligentfire:xml" + xml + "-------------------------------");
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (jsonObject.containsKey("result") && !jsonObject.getBoolean("result")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        return RespEntity.success(jsonObject);
    }

    //消防物联网:传参get post
    public RespEntity fireFightingiotPOSTNoToken(JSONObject jsonParam, String configKey, String key, String gp, String getOrPost) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        logger.info("-----------------------------------------fireFightingiotPOSTNoToken:" + domain + "-------------------------------------------------");
        if (getOrPost.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (getOrPost.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        logger.info("-----------------------------------------fireFightingiotPOSTNoToken:" + xml + "-------------------------------------------------");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.getInteger("code") == 1) {
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            return RespEntity.success(jsonObject.get("data"));
        } else {
            return RespEntity.success();
        }
    }

    //消防物联网对接
    public RespEntity fireFightingiotTwo1(JSONArray jsonArray, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonArray.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (jsonObject.containsKey("result") && !jsonObject.getBoolean("result")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            return RespEntity.success(jsonObject.get("data"));
        } else {
            return RespEntity.success(jsonObject);
        }
//        return RespEntity.success(jsonObject);
    }

    /**
     * 消防之队对接
     * JSONObject版本
     *
     * @param jsonParam
     * @param configKey
     * @param key
     * @param gp
     * @return
     */
    public RespEntity fireFightingIotJson(JSONObject jsonParam, String configKey, String key, String gp, String token) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp) + "?" + "token=" + token;
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        Object object = JSON.parse(xml);
        if (object instanceof com.alibaba.fastjson.JSONObject) {
            com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) object;
            if (jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")) {
                return RespEntity.fail(jsonObject.getString("Msg"));
            }
            if (jsonObject.containsKey("result") && !jsonObject.getBoolean("result")) {
                return RespEntity.fail(jsonObject.getString("Msg"));
            }
        } else if (object instanceof com.alibaba.fastjson.JSONArray) {
            return RespEntity.success(object);
        }
        return RespEntity.success(object);
    }

    /**
     * @Author YangYu
     * @Description //消防支队处置专用
     * @Date Created in 14:42 2021/12/23
     * @Param [jsonParam, configKey, key, gp, getOrPost, token]
     */

    public RespEntity fireFightingIotJsonRest(JSONObject jsonParam, String configKey, String key, String gp, String getOrPost, String token) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp) + "?" + "token=" + token;
        String domain = ip + methodPath;
        String xml = "";
        if (getOrPost.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (getOrPost.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        if (xml.equals("")) {
            return RespEntity.success();
        } else {
            JSONObject jsonObject = JSONUtil.parseObj(xml);
            return RespEntity.success(jsonObject);
        }
    }

    /**
     * 消防之队对接
     * JSONArray版本
     *
     * @param jsonArray
     * @param configKey
     * @param key
     * @param gp
     * @return
     */
    public RespEntity fireFightingiotArray(JSONArray jsonArray, String configKey, String key, String gp, String token) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp) + "?" + "token=" + token;
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonArray.toJSONString(1));
        }
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (jsonObject.containsKey("result") && !jsonObject.getBoolean("result")) {
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            return RespEntity.success(jsonObject.get("data"));
        } else {
            return RespEntity.success(jsonObject);
        }
    }

    //组装数据：token版
    public com.alibaba.fastjson.JSONObject makeDataForToken(JSONObject jsonParam, String configKey, String configPg, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, configPg);
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET") || "getDecodeToken".equals(key) || "todayAlarm".equals(key)) {
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (state == 401) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("methodCodeFlag", "1");
            return errorObject;
        } else if (jsonObject.getInteger("code") == 1) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg", jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag", "1");
            return errorObject;
        }
        if (configKey.equals("business") || configKey.equals("check")) {
            com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONObject("data").toJSONString()));
            return data;
        }

        return jsonObject.getJSONObject("data");
    }

    /**
     * 烟感报警消音
     *
     * @param jsonParam
     * @param configKey
     * @param configPg
     * @param key
     * @param gp
     * @return
     */
    public RespEntity silencer(JSONObject jsonParam, String configKey, String configPg, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, configPg);
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.post(domain)
                .header("appId", ConfigKit.getStr("appId", "silencer"))
                .header("auth-version", ConfigKit.getStr("authVersion", "silencer"))
                .header("secret", ConfigKit.getStr("secret", "silencer"))
                .body(jsonParam.toJSONString(1))
                .execute();
        xml = httpResponse.body();
        logger.info("消音:" + xml);
        return RespEntity.success();
    }

    //组装数据
    public com.alibaba.fastjson.JSONObject makeData(JSONObject jsonParam, String configKey, String configPg, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, configPg);
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.get(domain)
                .header("Authorization", httpServletRequest.getHeader("Authorization"))
                .form(jsonParam)
                .execute();
        xml = httpResponse.body();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.getInteger("code") == 1) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg", jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag", "1");
            return errorObject;
        }
        if (configKey.equals("business") || configKey.equals("check")) {
            com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONObject("data").toJSONString()));
            return data;
        }

        return jsonObject.getJSONObject("data");
    }

    //组装数据:处理返回即可能是JSONObject又可能是JsonArray的情况
    public JSON makeDataForJSON(JSONObject jsonParam, String configKey, String configPg, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, configPg);
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = HttpUtil.get(domain, jsonParam);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.getInteger("code") == 1) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg", jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag", "1");
            return errorObject;
        }
        if (configKey.equals("business") || configKey.equals("check")) {
            com.alibaba.fastjson.JSONArray data = com.alibaba.fastjson.JSONArray.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString()));
            return data;
        }
        return jsonObject.getJSONArray("data");
    }

    //组装数据:处理返回即可能是JSONObject又可能是JsonArray的情况:token版
    public JSON makeDataForJSONForToken(JSONObject jsonParam, String configKey, String configPg, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, configPg);
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET") || "getDecodeToken".equals(key)) {
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (state == 401) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("methodCodeFlag", "1");
            return errorObject;
        } else if (jsonObject.getInteger("code") == 1) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg", jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag", "1");
            return errorObject;
        }
        if (configKey.equals("business") || configKey.equals("check")) {
            com.alibaba.fastjson.JSONArray data = com.alibaba.fastjson.JSONArray.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString()));
            return data;
        }
        return jsonObject.getJSONArray("data");
    }

    //组装数据:处理返回即可能是JSONObject又可能是JsonArray的情况:token版
    public JSON makeDataForJSONForTokenMethod(JSONObject jsonParam, String configKey, String configPg, String key, String gp, String postOrGet) {
        String ip = ConfigKit.getStr(configKey, configPg);
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (postOrGet.equalsIgnoreCase("GET")) {
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        } else if (postOrGet.equalsIgnoreCase("POST")) {
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (state == 401) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("methodCodeFlag", "1");
            return errorObject;
        } else if (jsonObject.getInteger("code") == 1) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg", jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag", "1");
            return errorObject;
        }
        if (configKey.equals("business") || configKey.equals("check")) {
            com.alibaba.fastjson.JSONArray data = com.alibaba.fastjson.JSONArray.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString()));
            return data;
        }
        return jsonObject.getJSONArray("data");
    }

    /**
     * 微信
     *
     * @param jsonParam
     * @param configKey
     * @param key
     * @param gp
     * @return
     */
    public com.alibaba.fastjson.JSONObject WeChat(Dict jsonParam, String configKey, String key, String gp, String getOrPost) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (getOrPost.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (getOrPost.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam);
            //xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        return jsonObject;
//        return RespEntity.success(jsonObject);
    }

    //check
    public Integer restEvaluation(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        Integer S = null;
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        return Integer.parseInt(xml);
    }

    /**
     * 设备导出时调用
     *
     * @param jsonParam
     * @param configKey
     * @param key
     * @param gp
     * @return
     */
    public com.alibaba.fastjson.JSONObject userInfo(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        return (com.alibaba.fastjson.JSONObject) jsonObject.get("data");
    }

    public Map<String, Object> restCheck(JSONObject jsonParam, String configKey, String key, String gp) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        return jsonObject;
    }



    /**
     * @Author YangYu
     * @Description REST
     * @Date Created in 15:38 2020/12/29
     * @Param [jsonParam, configKey, key, gp, getOrPost]
     */

    public RespEntity rest(JSONObject jsonParam, String configKey, String key, String gp, String getOrPost) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (getOrPost.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (getOrPost.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        if (xml.equals("")) {
            return RespEntity.success();
        } else {
            JSONObject jsonObject = JSONUtil.parseObj(xml);
            return RespEntity.success(jsonObject);
        }
    }
    /**
     * @Author YangYu
     * @Description 数据转发REST
     * @Date Created in 15:38 2020/12/29
     * @Param [jsonParam, configKey, key, gp, getOrPost]
     */

    public RespEntity dataPushRest(JSONObject jsonParam, String url, String getOrPost) {
        String xml = "";
        if (getOrPost.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(url, jsonParam,1500);
        } else if (getOrPost.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(url, jsonParam.toJSONString(1),1500);
        }
        if (xml.equals("")) {
            return RespEntity.success();
        } else {
            JSONObject jsonObject = JSONUtil.parseObj(xml);
            return RespEntity.success(jsonObject);
        }
    }
    public com.alibaba.fastjson.JSONObject makeDatas(JSONObject jsonParam, String configKey, String key, String gp, String getOrPost) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (getOrPost.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (getOrPost.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if (jsonObject.getInteger("code") == 1) {
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg", jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag", "1");
            return errorObject;
        }
        return jsonObject.getJSONObject("data");
    }

    /**
     * 涛思
     *
     * @param jsonParam
     * @param configKey
     * @param key
     * @param gp
     * @return
     */
    public com.alibaba.fastjson.JSONArray taos(JSONObject jsonParam, String configKey, String key, String gp, String postOrGet) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (postOrGet.equalsIgnoreCase("GET")) {
            xml = HttpUtil.get(domain, jsonParam);
        } else if (postOrGet.equalsIgnoreCase("POST")) {
            xml = HttpUtil.post(domain, jsonParam.toJSONString(1));
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        return (com.alibaba.fastjson.JSONArray) jsonObject.get("data");
    }


    /**
     * @Author YangYu
     * @Description IP广播调用（沃云）
     * @Date Created in 10:13 2022/3/25
     * @Param [jsonParam, configKey, key, gp, method]
     */

    public JSONObject IPBroadCast(JSONObject jsonParam, String configKey, String key, String gp, String method) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (method.equalsIgnoreCase("GET")) {
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        } else if (method.equalsIgnoreCase("DELETE")) {
            httpResponse = HttpRequest.delete(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }else if (method.equalsIgnoreCase("POST")) {
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        if (xml.substring(0,1).equals("[")){
            JSONArray jsonArray = JSONUtil.parseArray(xml);
            JSONObject jsonObject = (JSONObject)jsonArray.get(0);
            return jsonObject;
        } else {
            JSONObject jsonObject = JSONUtil.parseObj(xml);
            return jsonObject;
        }
    }


    /**
     * @Author YangYu
     * @Description 返回JsonArray
     * @Date Created in 9:22 2022/4/6
     * @Param [jsonParam, configKey, key, gp, method]
     */

    public JSONArray IPBroadCastJsonArray(JSONObject jsonParam, String configKey, String key, String gp, String method) {
        String ip = ConfigKit.getStr(configKey, "config");
        String methodPath = FirefightingiotKit.getStr(key, gp);
        String domain = ip + methodPath;
        String xml = "";
        if (method.equalsIgnoreCase("GET")) {
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .form(jsonParam)
                    .execute();
        } else if (method.equalsIgnoreCase("DELETE")) {
            httpResponse = HttpRequest.delete(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }else if (method.equalsIgnoreCase("POST")) {
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", httpServletRequest.getHeader("Authorization"))
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        JSONArray jsonArray = JSONUtil.parseArray(xml);
        return jsonArray;
    }
}
